// 会议核心处理逻辑
import {
    stopMeetting,
    livekit_main,
    closeMeettingMic,
    closeMeettingCamera,
} from './index'
import { messageBody } from './messageData'
import core from "@/core"
import { stopCallBack, handleCallMeet, renderMedia, getCurrentDate } from './common'
// import v3layer from '@/components/v3layer/index'
import store from '@/store'
// 被呼叫
import callMusic from '@/static/music/livekit/meeting_invite_notification.mp3'
//有人加入
import otherJoined from '@/static/music/livekit/meeting_other_joined.mp3'
//有人离开
import otherLeft from '@/static/music/livekit/meeting_other_left.mp3'
//你加入了
import youJoined from '@/static/music/livekit/meeting_you_joined.mp3'
//你离开了
import youLeft from '@/static/music/livekit/meeting_you_left.mp3'

//实例化一个音频播放器对象
const audio = new Audio();

const unit8ToString = (unit8) => {
    const decoder = new TextDecoder();
    // 将字节流解码为字符串
    const str = decoder.decode(unit8);
    // console.log(str); // 输出结果为 "Hello"
    return str
}
export const livekit_main_implementation = (data) => {
    try {
        livekit_main(data, (room) => {
			console.log('准备就绪',room)
            data.meetingReading = false
            data.enterTime = getCurrentDate()
            room.participants.forEach(participant => { // 获取除了自己以外所有人员列表
                const audioTracks = Array.from(participant.tracks.values()).filter(track => track.kind === 'audio' || track.kind === 'video')
				// if(){}
					if(participant.identity == data.chatId){
						data.otherVideo = participant.isCameraEnabled;
						data.otherVoice = participant.isMicrophoneEnabled
					}
	//             const roomData = {
    //                 id: participant.identity,
    //                 name: participant.name,
    //                 muted: !participant.isMicrophoneEnabled,
    //                 videoMuted: !participant.isCameraEnabled,
    //                 isScreenShareEnabled: participant.isScreenShareEnabled,
    //                 isJoin: true
    //             }
    //             const isExit = !!data.roomList.find(item => item.id == roomData.id)
    //             if (!isExit) data.roomList.push(roomData)
				// data.allRoomList.push({id: participant.identity, name: participant.name})
    //             data.isScreenShareEnabled = !!data.roomList.find(item => item.isScreenShareEnabled && item.id != store.getters.user.id)
                data.$nextTick(() => {
                    audioTracks.forEach(audioTrack => {
                        const element = audioTrack.track.attach();
                        renderMedia(participant.identity, element, audioTrack.track.kind, participant.isScreenShareEnabled)
                    });
                })
            });
        }, (publication, participant) => { // 本地创建监听
            console.log('本地创建监听', participant)
			if(participant.identity == data.chatId){
				data.otherVideo = participant.isCameraEnabled;
				data.otherVoice = participant.isMicrophoneEnabled
			}
			
            // const roomList = data.roomList.map(item => {
            //     if (item.id == store.getters.user.id) {
            //         item.muted = !participant.isMicrophoneEnabled
            //         item.videoMuted = !participant.isCameraEnabled
            //         item.isScreenShareEnabled = participant.isScreenShareEnabled
            //         item.isJoin = true
            //         data.myRoom.muted = !participant.isMicrophoneEnabled
            //         data.myRoom.videoMuted = !participant.isCameraEnabled
            //         data.myRoom.isScreenShareEnabled = participant.isScreenShareEnabled
            //     }
            //     return item
            // })
            // data.roomList = roomList
			if(publication.track.kind == 'audio' && participant.identity == store.getters.user.id) return;
            data.$nextTick(() => {
                renderMedia(participant.identity, publication.track.attach(), publication.track.kind, participant.isScreenShareEnabled)
            })
        }, (participant) => {
            console.log('新加入',participant);
			
			
			
			
			data.palyingEnd = true;
            playAudio(2);
			
   //          const isExit = !!data.roomList.find(item => item.id == participant.identity)
			// const isAllExit = !!data.allRoomList.find(item => item.id == participant.identity)
   //          const roomData = {
   //              id: participant.identity,
   //              name: participant.name,
   //              muted: !participant.isMicrophoneEnabled,
   //              videoMuted: !participant.isCameraEnabled,
   //              isScreenShareEnabled: participant.isScreenShareEnabled,
   //              isJoin: true
   //          }
   //          if (!isExit) data.roomList.push(roomData)
			// if (!isAllExit) data.allRoomList.push({id: participant.identity, name: participant.name})
   //          if (isExit) {
   //              data.roomList = data.roomList.map(item => {
   //                  if (item.id == participant.identity) {
   //                      item.muted = !participant.isMicrophoneEnabled
   //                      item.videoMuted = !participant.isCameraEnabled
   //                      item.isScreenShareEnabled = participant.isScreenShareEnabled
   //                      item.isJoin = true
   //                  }
   //                  return item
   //              })
   //          }
        }, (track, publication, participant) => { // 添加新进入媒体执行两次
            console.log('新人媒体流订阅',participant)
			if(participant.identity == data.chatId){
				data.otherVideo = participant.isCameraEnabled;
				data.otherVoice = participant.isMicrophoneEnabled
			}
            // const roomList = data.roomList.map(item => {
            //     if (item.id == participant.identity) {
            //         item.muted = !participant.isMicrophoneEnabled
            //         item.videoMuted = !(participant.isCameraEnabled || participant.isScreenShareEnabled)
            //         item.isScreenShareEnabled = participant.isScreenShareEnabled
            //     }
            //     return item
            // })
            // data.isScreenShareEnabled = !!roomList.find(item => item.isScreenShareEnabled && item.id != store.getters.user.id)
            // data.roomList = roomList
            data.$nextTick(() => {
                const element = track.attach();
                renderMedia(participant.identity, element, track.kind, participant.isScreenShareEnabled)
            })
        }, (publication, participant,) => { // 监听视频音频启用
            console.log("监听视频音频启用",publication, participant)
			if(participant.identity == data.chatId){
				data.otherVideo = participant.isCameraEnabled;
				data.otherVoice = participant.isMicrophoneEnabled
			}
     //        const roomList = data.roomList.map(item => {
     //            if (item.id == participant.identity) {
     //                item.muted = !participant.isMicrophoneEnabled
     //                item.videoMuted = !participant.isCameraEnabled
     //                item.isScreenShareEnabled = participant.isScreenShareEnabled
					// if(data.screenVideoId == participant.identity){
					// 	data.screenVideoId = null;
					// }
     //            }
     //            return item
     //        })
     //        data.roomList = roomList
        }, (participant) => {// 监听有人离开
            console.log('有人离开',participant);
			
			
			data.otherHangUp();
            // playAudio(3)
            // data.roomList = data.roomList.filter(item => {
            //     if (item.id != participant.identity) {
            //         return item
            //     }
            // })

            // if(data.screenVideoId == participant.identity) data.screenVideoId = null;

        }, (speakers) => { // 监听 有人说话
            // if (speakers.length == 0) {
            //     data.roomList = data.roomList.map(item => {
            //         item.active = false
            //         return item
            //     })
            //     return
            // }
            // speakers.forEach(speaker => {
            //     data.roomList = data.roomList.map(item => {
            //         item.active = false
            //         if (item.id == speaker.identity) {
            //             item.active = true
            //         }
            //         return item
            //     })
            // })
        }, (publication, participant) => {// 监听视频本地共享屏幕开启关闭
            console.log('监听视频共享屏幕开启关闭', participant)
      //       setTimeout(() => {
      //           const roomList = data.roomList.map(item => {
      //               if (item.id == participant.identity) {
      //                   item.isScreenShareEnabled = participant.isScreenShareEnabled
      //                   item.videoMuted = !participant.isCameraEnabled
      //                   item.muted = !participant.isMicrophoneEnabled
      //                   data.isScreenShareEnabled = participant.isScreenShareEnabled
						// if(data.screenVideoId == participant.identity){
						// 	data.screenVideoId = null;
						// }
      //               }
      //               return item
      //           })
      //           console.log(roomList)
      //           data.roomList = roomList
      //       }, 300)
        }, (metadata) => { // 禁言
            data.roomInfo.muted = JSON.parse(metadata).muted
            if (data.roomInfo.uid == store.getters.user.id) return
            handleMute(data)
        }, (dataPacket) => {
			return;
            // console.log(dataPacket)
            const rmessage = JSON.parse(unit8ToString(dataPacket))
            console.log(rmessage)
            if (rmessage.fromUid == store.getters.user.id) return
            if (rmessage.action == 'MESSAGE') {
                const participant = data.roomList.find(item => item.id == rmessage.fromUid)
                const message = messageBody({ sender: data.roomTag, name: participant.name, receiver: rmessage.fromUid, content: rmessage.content })
                data.messageList.push(message)
                if(!data.isShowChat) data.isChatRed = true;
                data.scrollBottom();
            } else if (rmessage.action == 'REJECT') { // 有人拒绝加入
                data.roomList = data.roomList.filter(item => {
                    if (item.id != rmessage.fromUid) {
                        return item
                    }
                })
            } else if (rmessage.action == 'INVITE') { // 收到有人被邀请加入消息
                let invites = []
                rmessage.content = JSON.parse(rmessage.content)
                Object.keys(rmessage.content).forEach(item => {
                    const invite = {
                        id: item,
                        name: rmessage.content[item],
                        muted: true,
                        videoMuted: true,
                        isScreenShareEnabled: false,
                        isJoin: false
                    }
                    invites.push(invite)
                })
                // console.log(invites)
                data.roomList = [...data.roomList, ...invites]
                // console.log(data.roomList)
            } else if (rmessage.action == 'REMOVE') { // 自己被移除
                stopMeetting(() => {
                    stopCallBack(data)
                })
            } else if (rmessage.action == 'FINISH') { // 会议完成结束
                stopMeetting(() => {
                    stopCallBack(data)
                })
            } else if (rmessage.action == 'AUDIO_OFF' || rmessage.action == 'AUDIO_ON') { // 关闭成员麦克风
                if (rmessage.action == 'AUDIO_ON') {
				core.confirm('主持人想要您解除静音', '解除静音', async () => {
					closeMeettingMic(2, (muted) => {
						data.roomList = data.roomList.map(item => {
							if (item.id == data.myRoom.id) {
								item.muted = !muted
							}
							return item
						})
					})
				})
              
				} else {
                    closeMeettingMic(2, (muted) => {
                        data.roomList = data.roomList.map(item => {
                            if (item.id == data.myRoom.id) {
                                item.muted = !muted
                            }
                            return item
                        })
                    })
                }

            } else if (rmessage.action == 'CAMERA_OFF' || rmessage.action == 'CAMERA_ON') { // 开启成员麦克风
                if (rmessage.action == 'CAMERA_ON') {
					core.confirm('主持人想要您您开启视频', '开启视频', async () => {
						closeMeettingCamera((muted) => {
							data.roomList = data.roomList.map(item => {
								if (item.id == data.myRoom.id) {
									item.videoMuted = !muted
								}
								return item
							})
						})
					})
               
                
				} else {
                    closeMeettingCamera((muted) => {
                        data.roomList = data.roomList.map(item => {
                            if (item.id == data.myRoom.id) {
                                item.videoMuted = !muted
                            }
                            return item
                        })
                    })
                }
            }
        },()=>{
			console.log('房间准备已就绪------》》')
			let params = {
			    roomTag: data.roomTag,
			    member: data.memberParams
			}
			if(data.meetType == 'quick' && data.roomInfo.uid == data.user.id){
				console.log('livekit_main',data)
				handleCallMeet(params)
			} 
		}
		)
		
    
	} catch (error) {
        console.log(error)
		core.toast('设备占用或者没有设备');
     
        stopMeetting(() => {
            stopCallBack(data)
        })
    }
}

//打开关闭音频
const handleMute = (data) => {
    closeMeettingMic(data.muted ? 1 : 0, (muted) => {
        data.myRoom.muted = !muted
        data.roomList = data.roomList.map(item => {
            if (item.id == data.myRoom.id) {
                item.muted = !muted
            }
            return item
        })
    })
}

const playAudio = async (type) => {
    console.log('开始播放音乐', type)
    audio.pause()
    if (type == 1) {
        audio.src = callMusic
        audio.loop = true
        audio.addEventListener('ended', () => { })
        setTimeout(() => {
            audio.play() // 播放
        }, 500)
    }else{
        if(type ==2){ //有人加入
            audio.src = otherJoined
        }else if(type == 3){//有人离开
            audio.src = otherLeft
        }else if(type == 4){//你加入了
            audio.src = youJoined
        }else if(type == 5){//你离开了
            audio.src = youLeft
        }
        audio.loop = false
        audio.addEventListener('ended', () => {
            audio.pause()
        })
        setTimeout(() => {
            audio.play() // 播放
        }, 500)
    }
}